import { ref, inject } from 'vue'
import OSS from "ali-oss"
export default function () {
  const $api = inject("$api");
  //获取stsToken
  let ossObj = ref({})
  const initOssClient = async () => {
    let res = await $api.voucher()
    if (res.code === 1) {
      ossObj.value = res.data
      return ossObj.value
    }
  }
  //初始化oss（公有）
  let bucketAlbumOss = ref({})
  const initOssAlbumClient = async (loading) => {
    let res = await initOssClient()
    return bucketAlbumOss.value = new OSS({
      bucket: res.bucketAlbum,
      accessKeyId: res.accessKeyId, // '<access-key-id>',
      accessKeySecret: res.accessKeySecret, // '<access-key-secret>',
      stsToken: res.securityToken, //'<security-token>'
      endpoint: res.endpoint,
      objectNamePrefix: res.objectNamePrefix,
      refreshSTSToken: async () => {
        const refreshToken = await $api.voucher(loading)
        return {
          accessKeyId: refreshToken.data.accessKeyId, // '<access-key-id>',
          accessKeySecret: refreshToken.data.accessKeySecret, // '<access-key-secret>',
          stsToken: refreshToken.data.securityToken, //'<security-token>'
        }
      },
      refreshSTSTokenInterval: 10 * 60 * 1000,
    })
  }
  //初始化oss（私有）
  let bucketCertiOss = ref({})
  const initOssCertiClient = async (loading) => {
    let res = await initOssClient()
    return bucketCertiOss.value = new OSS({
      bucket: res.bucketCerti,
      accessKeyId: res.accessKeyId, // '<access-key-id>',
      accessKeySecret: res.accessKeySecret, // '<access-key-secret>',
      stsToken: res.securityToken, //'<security-token>'
      endpoint: res.endpoint,
      objectNamePrefix: res.objectNamePrefix,
      refreshSTSToken: async () => {
        const refreshToken = await $api.voucher(loading)
        return {
          accessKeyId: refreshToken.data.accessKeyId, // '<access-key-id>',
          accessKeySecret: refreshToken.data.accessKeySecret, // '<access-key-secret>',
          stsToken: refreshToken.data.securityToken, //'<security-token>'
        }
      },
      refreshSTSTokenInterval: 10 * 60 * 1000,
    })
  }
  return {
    ossObj,
    initOssClient,
    bucketAlbumOss,
    initOssAlbumClient,
    bucketCertiOss,
    initOssCertiClient,
  }
}